package org.spring.flower.resume.message;


import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slfj.Slfj;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = "${mq.config.queue}", autoDelete = "false"),
        key = "${mq.config.routeKey}",
        exchange = @Exchange(value = "${mq.config.exchange}", type = ExchangeTypes.DIRECT)))
public class ResumeDirectReceiver {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @RabbitHandler
    public void getMessage(String msg, Channel
            channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag, Message message) {
        log.info("收到消息{}", msg);
        try {
            /**
             * deliveryTag: 代表channel的唯一标识
             * multiple: 是否要批处理,false表示一次性确认
             */
            int i = 1 / 0;
            channel.basicAck(tag, false);
            //需要重试则直接抛出异常不用catch
        } catch (Exception e) {
            log.error("消费出现异常{}", e.getMessage());
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            log.info("redelivered value is {}", redelivered);
            /**
             * 第一次redelivered:false
             * 之前失败的,重启消费者后redelivered:true
             */
            try {
                if (redelivered) {
                    channel.basicReject(tag, false);
                    rabbitTemplate.convertAndSend(RabbitMqDeadLetterConfig.DL_EXCHANGE, RabbitMqDeadLetterConfig.DL_ROUTE_KEY, message);
                }

                if (!redelivered) {
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
                }
            } catch (Exception ex) {
                log.error("处理redelivered异常{}", e);
            }
        }
    }
}
